import { createRouter, createWebHistory } from "vue-router";
import axios from "axios";
import store from "@/store";

const Home = () => import("@/views/Home.vue" /* webpackChunkName: "home" */);
const Login = () => import("@/views/Login.vue" /* webpackChunkName: "login" */);
const Signup = () =>
  import("@/views/Signup.vue" /* webpackChunkName: "signup" */);
const ColumnDetail = () =>
  import("@/views/ColumnDetail.vue" /* webpackChunkName: "column-detail" */);
const PostDetail = () =>
  import("@/views/PostDetail.vue" /* webpackChunkName: "post-detail" */);
const CreatePost = () =>
  import("@/views/CreatePost.vue" /* webpackChunkName: "create-post" */);

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: "/",
      name: "home",
      component: Home,
    },
    {
      path: "/login",
      name: "login",
      component: Login,
      meta: { redirectAlreadyLogin: true }, // 路由元信息 https://next.router.vuejs.org/zh/guide/advanced/meta.html
    },
    {
      path: "/signup",
      name: "signup",
      component: Signup,
      meta: { redirectAlreadyLogin: true },
    },
    {
      path: "/create",
      name: "create",
      component: CreatePost,
      meta: { requiredLogin: true },
    },
    {
      path: "/column/:id",
      name: "column",
      component: ColumnDetail,
    },
    {
      path: "/posts/:id",
      name: "post",
      component: PostDetail,
    },
  ],
});

// 导航守卫 https://next.router.vuejs.org/zh/guide/advanced/navigation-guards.html
router.beforeEach(async (to, from, next) => {
  const { user, token } = store.state;
  const { redirectAlreadyLogin, requiredLogin } = to.meta;

  // 判断token是否存在，并且用户还未登录
  if (!user.isLogin) {
    if (token) {
      // 设置header头
      axios.defaults.headers.common.Authorization = `Bearer ${token}`;
      try {
        await store.dispatch("fetchCurrentUser");
        redirectAlreadyLogin ? next("/") : next();
      } catch {
        store.commit("logout");
        next("login");
      }
    } else {
      requiredLogin ? next("login") : next();
    }
  } else {
    redirectAlreadyLogin ? next("/") : next();
  }
});

export default router;
